package com.bdqn.ch02.SZ.sz1;

import com.bdqn.ch02.SL.XMLParse;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

/**
 * DOMTest
 *
 * @aurhor Administrator  whs
 * @since 2024/7/1
 */
public class DOMTest {
    Document doc = null ;
    // 获取DOM树
    public void getDocument(){
        //1.获取解析器工厂
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        //2.获取解析器
        try {
            DocumentBuilder builder = factory.newDocumentBuilder();
            //3.加载DOM树
            doc = (Document) builder.parse("src/com/bdqn/ch02/SZ/sz1/手机品牌.xml");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示 XML 中所有信息
     */
    public void showInfo(){
        //获取<Brand> 的所有节点集合
        NodeList nodeList = doc.getElementsByTagName("Brand");
        for (int i=0 ; i<nodeList.getLength(); i++){
            // i=0 时得到第一个Brand节点
            Node brand = nodeList.item(i);
            Element brandEle = (Element) brand;
            // 读取此节点的name属性 <Brand name="name"
            String brandStr = brandEle.getAttribute("name");

            //得到 Brand节点下的子节点
            NodeList types = brandEle.getChildNodes();
            for (int j=0 ; j<types.getLength(); j++){
                //得到 Brand 节点下的第一个子节点，Type
                Node type = types.item(j);
                if (type.getNodeType()==Node.ELEMENT_NODE){   // 判断是否是元素节点
                    Element typeEle = (Element) type;
                    String typeStr = typeEle.getAttribute("name");
                    System.out.println("手机："+brandStr+typeStr);

                }
            }
        }
    }

    public static void main(String[] args) {
        DOMTest domTest = new DOMTest();
        domTest.getDocument();
        domTest.showInfo();

    }
}
